package com.jzr.netty.controller;

import com.jzr.common.entity.vo.Result;
import com.jzr.common.util.U;
import com.jzr.netty.base.DeviceMap;
import com.jzr.netty.common.base.DeviceLive;
import com.jzr.netty.common.protocol.ReloadDataDeptRequest;
import com.jzr.netty.common.protocol.ReloadDataRequest;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {
    @GetMapping("/list")
    public List<DeviceLive> list(String deptCode, Integer deviceType){
        return DeviceMap.getDeviceLive(deptCode,deviceType);
    }
    @PostMapping("reloadData")
    public Result<String> reloadData(@RequestBody ReloadDataDeptRequest request){
        try {
            String deviceIp = request.getDeviceIp();

            ReloadDataRequest newRequest = new ReloadDataRequest();
            BeanUtils.copyProperties(request,newRequest);
            newRequest.setDeviceIp(null);

            int count = 0;
            if(U.isNotBlank(deviceIp)){
                String[] ipList = deviceIp.split(",");
                for(String ip : ipList){
                    SocketChannel channel = DeviceMap.get(ip);
                    if(channel != null){
                        channel.writeAndFlush(newRequest);
                        count++;
                    }
                }
            }else if(U.isNotBlank(request.getDeviceType())){
                List<SocketChannel> list = DeviceMap.getSocketChannelList(request.getDeptCode(),request.getDeviceType());
                for(SocketChannel channel : list){
                    channel.writeAndFlush(newRequest);
                    count++;
                }
            }
            return Result.success("成功,Reload:"+count);
        }catch (Exception ex){
            ex.printStackTrace();
            return Result.fail("失败,"+ex.getMessage());
        }
    }

}
